package com.yanftch.hdc_tools.command

import com.yanftch.hdc_tools.common.MessageDelegate
import com.yanftch.hdc_tools.common.executeCommand
import com.yanftch.hdc_tools.common.finalCommandLine
import com.yanftch.hdc_tools.common.isCommandSucceed
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking

class RestartAppWithDebuggerCommand : Command {
    override fun run(commandContext: CommandContext): Boolean {
        with(commandContext) {
            try {
                runBlocking {
                    val stop = async { executeCommand(finalCommandLine(hdcPath, force_stop, bundleName)) }.await()
                    val startWithDebugger = async { executeCommand(finalCommandLine(hdcPath, hdc_aa_start_with_debugger(bundleName, defaultAbility))) }.await()
                    if (stop.isCommandSucceed() && startWithDebugger.isCommandSucceed()) {
                        MessageDelegate.info("restart app with debugger success.", action)
                        // 启动APP
                        HdcToolKit.startApp(project, action)
                    } else {
                        MessageDelegate.error("restart app with debugger failed. $stop; $startWithDebugger", action)
                    }
                }

            } catch (e: Exception) {
                MessageDelegate.error("restart app with debugger error: ${e.message}", action)
            }
        }
        return false
    }
}